package resources;

import java.io.File;
import java.io.FileInputStream;
import java.io.PrintWriter;

import org.apache.pdfbox.cos.COSDocument;
import org.apache.pdfbox.pdfparser.PDFParser;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.util.PDFTextStripper;


//PDF text parser thread
public class PDFTextParser  {
	PDFParser parser;
    String parsedText;
    PDFTextStripper pdfStripper;
    PDDocument pdDoc;
    COSDocument cosDoc;
    PDDocumentInformation pdDocInfo;
	
	
	
	public PDFTextParser() {
		
	}
	
    // Extract text from PDF Document
   public String pdftoText(String fileName) {
        File f = new File(fileName);
        
        if (!f.isFile()) {
            return null;
        }
        
        try {
            parser = new PDFParser(new FileInputStream(f));
        } catch (Exception e) {
            return null;
        }
        
        try {
            parser.parse();
            cosDoc = parser.getDocument();
            pdfStripper = new PDFTextStripper();
            pdDoc = new PDDocument(cosDoc);
            parsedText = pdfStripper.getText(pdDoc); 
            if (cosDoc != null) cosDoc.close();
            if (pdDoc != null) pdDoc.close();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                   if (cosDoc != null) cosDoc.close();
                   if (pdDoc != null) pdDoc.close();
               } catch (Exception e1) {
               e.printStackTrace();
            }
            return null;
        }      
        return parsedText;
    }
    
    // Write the parsed text from PDF to a file
    void writeTexttoFile(String pdfText, String fileName) {
    	try {
    		PrintWriter pw = new PrintWriter(fileName);
    		pw.print(pdfText);
    		pw.close();    	
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	pdfText=null;
    }
    
    //Extracts text from a PDF Document and writes it to a text file
    public void go(String source, String destination) {
        
       
        String pdfToText = pdftoText(source);
        
        if (pdfToText == null) {
        }
        else {
        	writeTexttoFile(pdfToText, destination);
        }
    }  
}
